package com.topcent.tioxyc.consumer;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.vo.XiaoSYing;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: weidian
 * @date: 2024/11/28 09:46
 * @Description: 收款单消费类
 */
@Component
@RabbitListener(queues = "Payments")
@Slf4j
public class PaymentsConsumer {
    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";
    private static final String DATA_DELETE = "data_remove";

    @RabbitHandler
    public void handleMessage(String msg, Channel channel, Message message) throws IOException {
        try {
            // 处理 payload 消息
            //System.out.println("Received payload: " + msg);
            // 在这里执行具体的业务逻辑

            // 在这里处理推送来的数据
            JSONObject payloadJSON = JSONUtil.parseObj(msg);
            String op = payloadJSON.getStr("op");
            String data = payloadJSON.getStr("data");

            if (DATA_UPDATE.equals(op)) {
                update(data);
                xsuodate(data);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("Message acknowledged");
        } catch (Exception e) {
            // 处理异常并拒绝消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            System.err.println("发送消息失败，重试中 " + e.getMessage());
        }
    }

    private void update(String data) {
        Payments payments = JSONUtil.toBean(data, Payments.class);
        if (payments.getFlowState() == 1) {
            Header[] headers = ConnmeUtils.createHeaders();
            String s = ConnmeUtils.liuChen(payments.get_id());
            payments.set_widget_1732757161498(s);
            Payments payments1 = ConnmeUtils.updateFields(payments);
            Map<String, Object> parameterInster = new HashMap<>();
            parameterInster.put("app_id", "669cb709a73cc1289c49800e");
            parameterInster.put("entry_id", "669cb70dab60aa3f4a7bb8b2");
            parameterInster.put("is_start_trigger", "true");
            parameterInster.put("data_id", payments1.get_id());
            payments1.set_id(null);
            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(payments1));
            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
            log.info("收款单更新的数据{}", jsonSalee);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
        }
    }
    private void xsuodate(String data) {
        Header[] headers = ConnmeUtils.createHeaders();
        SalesCalculation salesCalculation = JSONUtil.toBean(data, SalesCalculation.class);

        if (salesCalculation.getFlowState()!=1){
            return;
        }

        Map<String, Map<String,Double>> yushou = new HashMap<>();
        Map<String,  Map<String,Double>> weikuan = new HashMap<>();


        for (SalesCalculation.OrderPrepayment orderPrepayment : salesCalculation.get_widget_1721546510495()) {
            if (yushou.containsKey(orderPrepayment.get_widget_1721546510504())){
                Map<String, Double> stringDoubleMap = yushou.get(orderPrepayment.get_widget_1721546510504());
                if (stringDoubleMap.containsKey(orderPrepayment.get_widget_1721616942683())){
                    Double aDouble = yushou.get(orderPrepayment.get_widget_1721546510504()).get(orderPrepayment.get_widget_1721616942683());
                    stringDoubleMap.put(orderPrepayment.get_widget_1721616942683(),orderPrepayment.get_widget_1721546510520()+aDouble);
                }else {
                    stringDoubleMap.put(orderPrepayment.get_widget_1721616942683(),orderPrepayment.get_widget_1721546510520());
                }

            }else {
                Map<String,Double> yushou001 = new HashMap<>();
                yushou001.put(orderPrepayment.get_widget_1721616942683(),orderPrepayment.get_widget_1721546510520());
                yushou.put(orderPrepayment.get_widget_1721546510504(),yushou001);
            }
        }

        chuliYuSuan(headers, yushou,true);


        for (SalesCalculation.OrderFinalPayment orderFinalPayment : salesCalculation.get_widget_1721548605263()) {
            if (weikuan.containsKey(orderFinalPayment.get_widget_1721548605264())){
                Map<String, Double> stringDoubleMap = weikuan.get(orderFinalPayment.get_widget_1721548605264());
                if (stringDoubleMap.containsKey(orderFinalPayment.get_widget_1721616942684())){
                    Double aDouble = weikuan.get(orderFinalPayment.get_widget_1721548605264()).get(orderFinalPayment.get_widget_1721616942684());
                    stringDoubleMap.put(orderFinalPayment.get_widget_1721616942684(),orderFinalPayment.get_widget_1721548605266()+aDouble);
                }else {
                    stringDoubleMap.put(orderFinalPayment.get_widget_1721616942684(),orderFinalPayment.get_widget_1721548605266());
                }

            }else {
                Map<String,Double> yushou001 = new HashMap<>();
                yushou001.put(orderFinalPayment.get_widget_1721616942684(),orderFinalPayment.get_widget_1721548605266());
                weikuan.put(orderFinalPayment.get_widget_1721548605264(),yushou001);
            }
        }

        chuliYuSuan(headers, weikuan,false);

    }

    private void chuliYuSuan(Header[] headers, Map<String, Map<String, Double>> weikuan,boolean ister) {
        weikuan.forEach((key, innerMap) -> {
            try {
                Map<String, Object> parameterCx = new HashMap<>();
                parameterCx.put("app_id", "667230ad22a8581756b77d52");
                parameterCx.put("entry_id", "669e17aa09cd4f4e279d4d5d");
                log.info("Querying based on key: " + key);
                List<SalesOrderKu> salesOrderKus = PurchaseCommunity.queryBased(parameterCx, headers, key, "_widget_1718759603973", SalesOrderKu.class);

                if (salesOrderKus == null || salesOrderKus.isEmpty()) {
                    log.warn("没找到销售订单" + key);
                    return; // 继续下一个key
                }

                innerMap.forEach((innerKey, value) -> {
                    log.info("处理内键：" + innerKey + ", value: " + value);
                    SalesOrderKu salesOrderKu = salesOrderKus.get(0);
                    if (salesOrderKu == null) {
                        log.error("SalesOrderKu 的键为 null：" + key);
                        return;
                    }

                    List<SalesOrderKu.OrderDetail> orderDetails = salesOrderKu.get_widget_1718759603981();
                    if (orderDetails == null) {
                        log.error("SalesOrderKu 的订单详细信息为空：" + salesOrderKu);
                        return;
                    }

                    double zong=0;

                    for (SalesOrderKu.OrderDetail orderDetail : orderDetails) {
                        if (orderDetail == null) {
                            log.error("订单详情列表中订单详情为空。");
                            continue;
                        }

                        if (orderDetail.get_widget_1718759603995() == null) {
                            log.error("对于订单详细信息，订单详细信息内键为空：{}", orderDetail);
                            continue;
                        }

                        if (orderDetail.get_widget_1718759603995().equals(innerKey)) {
                            if (ister) {
                                if (orderDetail.get_widget_1721982279364() == null) {
                                    orderDetail.set_widget_1721982279364(value);
                                } else {
                                    orderDetail.set_widget_1721982279364(value + orderDetail.get_widget_1721982279364());
                                }

                            } else {
                                if (orderDetail.get_widget_1721982279365() == null) {
                                    orderDetail.set_widget_1721982279365(value);
                                } else {
                                    orderDetail.set_widget_1721982279365(value + orderDetail.get_widget_1721982279365());
                                }

                            }
                            if (orderDetail.get_widget_1721982279365() != null && orderDetail.get_widget_1721982279364() != null){
                                orderDetail.set_widget_1722241817628(orderDetail.get_widget_1721639369902()-orderDetail
                                        .get_widget_1721982279365()-orderDetail.get_widget_1721982279364());
                                zong=zong+orderDetail.get_widget_1721982279365()-orderDetail.get_widget_1721982279364();
                            }


                            log.info("更新订单详情：{}", orderDetail);
                        }
                    }
                    if (salesOrderKu.get_widget_1718759603984()-zong<=0){
                        salesOrderKu.set_widget_1734504746939("是");
                        Map<String, Object> parameterCxv = new HashMap<>();
                        parameterCxv.put("app_id", "669cb709a73cc1289c49800e");
                        parameterCxv.put("entry_id", "674d839475ae49b66713aadb");
                        HashMap<String, String> communti = new HashMap<>();
                        communti.put("_widget_1731918876993", salesOrderKu.get_widget_1718759603973());
                        List<DeliveryVoucher> deliveryVouchers = PurchaseCommunity.queryBased(parameterCxv, headers, communti, DeliveryVoucher.class);
                        if (deliveryVouchers != null && !deliveryVouchers.isEmpty()){
                            for (DeliveryVoucher deliveryVoucher : deliveryVouchers) {
                                deliveryVoucher.set_widget_1734429312703("是");
                                Map<String, Object> parameterInster = new HashMap<>();
                                parameterInster.put("app_id", "669cb709a73cc1289c49800e");
                                parameterInster.put("entry_id", "674d839475ae49b66713aadb");
                                parameterInster.put("is_start_trigger", "true");
                                parameterInster.put("data_id", deliveryVoucher.get_id());
                                deliveryVoucher.set_id(null);
                                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(deliveryVoucher));
                                String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
                            }
                        }

                    }

                });


                Map<String, Object> parametereefsyy = new HashMap<>();
                parametereefsyy.put("app_id", "667230ad22a8581756b77d52");
                parametereefsyy.put("entry_id", "66a30b55ecb3bf2d5748208c");
                HashMap<String, String> communtidyy = new HashMap<>();
                communtidyy.put("_widget_1718759603973", key);
                List<XiaoSYing> xiaoSYings = PurchaseCommunity.queryBased(parametereefsyy, headers, communtidyy, XiaoSYing.class);
                if (xiaoSYings != null && !xiaoSYings.isEmpty()) {
                    for (XiaoSYing xiaoSYing : xiaoSYings) {
                        xiaoSYing.set_widget_1734673959092("是");
                        Map<String, Object> parameterInster = new HashMap<>();
                        parameterInster.put("app_id", "667230ad22a8581756b77d52");
                        parameterInster.put("entry_id", "66a30b55ecb3bf2d5748208c");
                        parameterInster.put("is_start_trigger", "true");
                        parameterInster.put("data_id", xiaoSYing.get_id());
                        xiaoSYing.set_id(null);
                        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(xiaoSYing));
                        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
                    }
                }

                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", "667230ad22a8581756b77d52");
                parameterInster.put("entry_id", "669e17aa09cd4f4e279d4d5d");
                parameterInster.put("is_start_trigger", "true");
                parameterInster.put("data_id", salesOrderKus.getFirst().get_id());
                salesOrderKus.getFirst().set_id(null);
                salesOrderKus.getFirst().set_widget_1718759603978(null);
                salesOrderKus.getFirst().set_widget_1718759603990(null);

                for (SalesOrderKu.OrderDetail orderDetail : salesOrderKus.getFirst().get_widget_1718759603981()) {
                    orderDetail.set_widget_1726803260151(orderDetail.get_widget_1726803260151().toString());
                }
                SalesOrderKu salesOrderKu = ConnmeUtils.updateFields(salesOrderKus.getFirst());

                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(salesOrderKu));
                String jsonSale = JSONUtil.toJsonStr(parameterInster);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
            } catch (Exception e) {
                log.error("处理销售订单出错" + key, e);
            }
        });


    }
}
